package client;

import gui.GUIControl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.util.Scanner;

import javax.net.SocketFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public class Client {
	private int port;
	private String host;
	private BufferedWriter bw;
	private BufferedReader br;
	private InputMasterClient inputMasterClient;
	private String myAccessRights;
	private GUIControl gc=null;
	private SSLSocketFactory ssocketFactory;

	public Client(int port, String host) {
		this.port = port;
		this.host = host;

	}
	public void logIn(String username, String keypass) throws IOException{
		ssocketFactory = null;
        try {
        	SSLContext ctx;
        	KeyManagerFactory kmf;
        	KeyStore ks;
        	char[] passphrase = keypass.toCharArray();
        	ctx = SSLContext.getInstance("TLS");
        	kmf = KeyManagerFactory.getInstance("SunX509");
        	ks = KeyStore.getInstance("JKS");
        	ks.load(new FileInputStream(username+"Keystore.jks"), passphrase);
        	kmf.init(ks, passphrase);
        	ctx.init(kmf.getKeyManagers(), null, null);
        	ssocketFactory = ctx.getSocketFactory();
        } catch (Exception e) {
        	throw new IOException("Login failure");
        } 
        connect();
	}
	public void connect() throws UnknownHostException, IOException {
		SSLSocket socket = (SSLSocket) ssocketFactory.createSocket(host, port);
		
		// Till server
		OutputStream out = socket.getOutputStream();
		OutputStreamWriter outputstreamwriter = new OutputStreamWriter(out);
		bw = new BufferedWriter(outputstreamwriter);
		
		// Från server
		InputStream inFromServer = socket.getInputStream();
		InputStreamReader inReader = new InputStreamReader(inFromServer);
		br = new BufferedReader(inReader);
		inputMasterClient = new InputMasterClient(br, this);
		inputMasterClient.start();
	}
	public void newInput(String fromServer) {
		if (fromServer.startsWith("%")) {
			System.out.println("Now authenticated at server as: "+fromServer);
			myAccessRights = fromServer.substring(0).trim();
			gc=new GUIControl(myAccessRights, bw);
		} else {
			gc.messageFromServer(fromServer);
		}
	}
}
